<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统监控仪表盘</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    
    <!-- Tailwind配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#722ED1',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        dark: '#1D2129',
                        'dark-2': '#272E3B',
                        'dark-3': '#4E5969',
                        light: '#F2F3F5'
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .animate-pulse-slow {
                animation: pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite;
            }
            .animate-number {
                transition: all 0.5s ease-out;
            }
            .grid-dashboard {
                grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            }
            .progress-bar {
                transition: width 0.5s ease-in-out;
            }
        }
    </style>
</head>
<body class="bg-dark text-light font-inter min-h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <header class="bg-dark-2 shadow-md sticky top-0 z-50 backdrop-blur-sm bg-dark/80">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <div class="flex items-center space-x-3">
                <i class="fa fa-microchip text-primary text-2xl"></i>
                <h1 class="text-xl font-bold text-white">系统监控仪表盘</h1>
            </div>
            <div class="flex items-center space-x-4">
                <button id="refreshBtn" class="bg-primary/20 hover:bg-primary/30 text-primary px-3 py-1.5 rounded-lg transition-all duration-300 flex items-center">
                    <i class="fa fa-refresh mr-2"></i>
                    <span>刷新</span>
                </button>
                <span id="updateTime" class="text-sm text-gray-400">更新于: --:--:--</span>
            </div>
        </div>
    </header>

    <main class="container mx-auto px-4 py-6 flex-grow">
        <!-- 系统状态概览 -->
        <section class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div class="bg-dark-2 rounded-xl p-5 shadow-lg hover:shadow-primary/20 hover:shadow-xl transition-all duration-300 border border-primary/10">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <h3 class="text-gray-400 text-sm font-medium">CPU 使用率</h3>
                        <p id="cpuPercent" class="text-3xl font-bold mt-1">0%</p>
                    </div>
                    <div class="bg-primary/20 p-2 rounded-lg">
                        <i class="fa fa-microchip text-primary"></i>
                    </div>
                </div>
                <div class="h-2 bg-dark-3 rounded-full overflow-hidden">
                    <div id="cpuBar" class="h-full bg-primary rounded-full progress-bar" style="width: 0%"></div>
                </div>
                <div class="mt-3 flex justify-between text-xs text-gray-400">
                    <span>物理核心: <span id="cpuCores">0</span></span>
                    <span>逻辑核心: <span id="cpuCoresLogical">0</span></span>
                </div>
            </div>

            <div class="bg-dark-2 rounded-xl p-5 shadow-lg hover:shadow-secondary/20 hover:shadow-xl transition-all duration-300 border border-secondary/10">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <h3 class="text-gray-400 text-sm font-medium">内存使用率</h3>
                        <p id="memoryPercent" class="text-3xl font-bold mt-1">0%</p>
                    </div>
                    <div class="bg-secondary/20 p-2 rounded-lg">
                        <i class="fa fa-memory text-secondary"></i>
                    </div>
                </div>
                <div class="h-2 bg-dark-3 rounded-full overflow-hidden">
                    <div id="memoryBar" class="h-full bg-secondary rounded-full progress-bar" style="width: 0%"></div>
                </div>
                <div class="mt-3 flex justify-between text-xs text-gray-400">
                    <span>已用: <span id="memoryUsed">0 GB</span></span>
                    <span>总计: <span id="memoryTotal">0 GB</span></span>
                </div>
            </div>

            <div class="bg-dark-2 rounded-xl p-5 shadow-lg hover:shadow-success/20 hover:shadow-xl transition-all duration-300 border border-success/10">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <h3 class="text-gray-400 text-sm font-medium">磁盘使用率</h3>
                        <p id="diskPercent" class="text-3xl font-bold mt-1">0%</p>
                    </div>
                    <div class="bg-success/20 p-2 rounded-lg">
                        <i class="fa fa-hdd-o text-success"></i>
                    </div>
                </div>
                <div class="h-2 bg-dark-3 rounded-full overflow-hidden">
                    <div id="diskBar" class="h-full bg-success rounded-full progress-bar" style="width: 0%"></div>
                </div>
                <div class="mt-3 flex justify-between text-xs text-gray-400">
                    <span>已用: <span id="diskUsed">0 GB</span></span>
                    <span>总计: <span id="diskTotal">0 GB</span></span>
                </div>
            </div>

            <div class="bg-dark-2 rounded-xl p-5 shadow-lg hover:shadow-warning/20 hover:shadow-xl transition-all duration-300 border border-warning/10">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <h3 class="text-gray-400 text-sm font-medium">网络流量</h3>
                        <div class="flex items-end space-x-2">
                            <p id="networkSent" class="text-2xl font-bold">0 KB/s</p>
                            <p id="networkRecv" class="text-xl font-bold text-gray-300">↓ 0 KB/s</p>
                        </div>
                    </div>
                    <div class="bg-warning/20 p-2 rounded-lg">
                        <i class="fa fa-wifi text-warning"></i>
                    </div>
                </div>
                <div class="mt-3 flex justify-between text-xs text-gray-400">
                    <span>发送: <span id="totalSent">0 MB</span></span>
                    <span>接收: <span id="totalRecv">0 MB</span></span>
                </div>
            </div>
        </section>

        <!-- CPU 历史图表 -->
        <section class="bg-dark-2 rounded-xl p-5 shadow-lg mb-8 border border-primary/10">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-lg font-bold">CPU 使用率历史</h2>
                <div class="text-sm text-gray-400">
                    <span id="chartRefresh">自动刷新: <span class="text-primary">开启</span></span>
                    <button id="toggleChartRefresh" class="ml-2 text-xs bg-primary/20 hover:bg-primary/30 text-primary px-2 py-1 rounded transition-colors">
                        <i class="fa fa-pause"></i>
                    </button>
                </div>
            </div>
            <div class="h-64">
                <canvas id="cpuChart"></canvas>
            </div>
        </section>

        <!-- 进程列表 -->
        <section class="bg-dark-2 rounded-xl p-5 shadow-lg border border-primary/10">
            <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-4 gap-4">
                <h2 class="text-lg font-bold">进程管理器</h2>
                <div class="flex items-center space-x-3 w-full md:w-auto">
                    <div class="relative flex-1 md:flex-none max-w-md">
                        <input type="text" id="processSearch" placeholder="搜索进程..." 
                               class="w-full bg-dark-3 border border-primary/20 rounded-lg px-4 py-2 pl-10 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50">
                        <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                    </div>
                    <div class="flex items-center space-x-2">
                        <span class="text-sm text-gray-400">排序:</span>
                        <select id="sortBy" class="bg-dark-3 border border-primary/20 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50">
                            <option value="cpu_percent">CPU 使用率</option>
                            <option value="memory_percent">内存使用率</option>
                            <option value="pid">PID</option>
                            <option value="name">名称</option>
                        </select>
                        <button id="sortOrder" class="bg-dark-3 border border-primary/20 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50">
                            <i class="fa fa-sort-desc"></i>
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-dark-3">
                    <thead>
                        <tr>
                            <th class="px-4 py-3 bg-dark-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider rounded-tl-lg">PID</th>
                            <th class="px-4 py-3 bg-dark-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">名称</th>
                            <th class="px-4 py-3 bg-dark-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">用户</th>
                            <th class="px-4 py-3 bg-dark-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">CPU (%)</th>
                            <th class="px-4 py-3 bg-dark-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">内存 (%)</th>
                            <th class="px-4 py-3 bg-dark-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">状态</th>
                            <th class="px-4 py-3 bg-dark-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider rounded-tr-lg">操作</th>
                        </tr>
                    </thead>
                    <tbody id="processTableBody">
                        <!-- 进程数据将通过JavaScript动态填充 -->
                        <tr class="animate-pulse">
                            <td colspan="7" class="px-4 py-8 text-center text-gray-400">
                                <i class="fa fa-spinner fa-spin mr-2"></i>加载进程中...
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <div id="noProcessesFound" class="hidden px-4 py-8 text-center text-gray-400">
                <i class="fa fa-search-minus mr-2"></i>未找到匹配的进程
            </div>
        </section>
    </main>

    <!-- 进程详情模态框 -->
    <div id="processDetailsModal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden backdrop-blur-sm">
        <div class="bg-dark-2 rounded-xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-hidden transform transition-all duration-300 scale-95 opacity-0" id="modalContent">
            <div class="flex justify-between items-center p-5 border-b border-dark-3">
                <h3 class="text-lg font-bold" id="modalTitle">进程详情</h3>
                <button id="closeModal" class="text-gray-400 hover:text-white transition-colors">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            <div class="p-5 overflow-y-auto max-h-[calc(90vh-120px)]" id="modalBody">
                <!-- 模态框内容将通过JavaScript动态填充 -->
                <div class="flex justify-center items-center h-40">
                    <i class="fa fa-spinner fa-spin text-3xl text-gray-400"></i>
                </div>
            </div>
            <div class="p-5 border-t border-dark-3 flex justify-end space-x-3">
                <button id="cancelTerminate" class="px-4 py-2 bg-dark-3 hover:bg-dark-3/80 text-white rounded-lg transition-colors">
                    取消
                </button>
                <button id="confirmTerminate" class="px-4 py-2 bg-danger hover:bg-danger/80 text-white rounded-lg transition-colors">
                    <i class="fa fa-stop-circle mr-2"></i>终止进程
                </button>
            </div>
        </div>
    </div>

    <!-- 操作结果提示 -->
    <div id="toastNotification" class="fixed bottom-5 right-5 bg-dark-2 shadow-lg rounded-lg p-4 transform translate-y-10 opacity-0 transition-all duration-300 z-50 max-w-xs">
        <div class="flex items-start">
            <div id="toastIcon" class="flex-shrink-0 pt-0.5">
                <i class="fa fa-check-circle text-success text-xl"></i>
            </div>
            <div class="ml-3">
                <h3 id="toastTitle" class="text-sm font-medium text-white">操作成功</h3>
                <div id="toastMessage" class="mt-1 text-sm text-gray-400">
                    进程已成功终止
                </div>
            </div>
            <button id="closeToast" class="ml-auto flex-shrink-0 text-gray-400 hover:text-white">
                <i class="fa fa-times"></i>
            </button>
        </div>
    </div>

    <script>
        // 全局变量
        let cpuChart;
        let sortOrder = 'desc';
        let lastNetworkData = null;
        let chartRefreshEnabled = true;
        let currentProcessPid = null;
        
        // DOM 元素
        const refreshBtn = document.getElementById('refreshBtn');
        const updateTime = document.getElementById('updateTime');
        const processSearch = document.getElementById('processSearch');
        const sortBy = document.getElementById('sortBy');
        const sortOrderBtn = document.getElementById('sortOrder');
        const processTableBody = document.getElementById('processTableBody');
        const noProcessesFound = document.getElementById('noProcessesFound');
        const processDetailsModal = document.getElementById('processDetailsModal');
        const modalContent = document.getElementById('modalContent');
        const modalTitle = document.getElementById('modalTitle');
        const modalBody = document.getElementById('modalBody');
        const closeModal = document.getElementById('closeModal');
        const confirmTerminate = document.getElementById('confirmTerminate');
        const cancelTerminate = document.getElementById('cancelTerminate');
        const toastNotification = document.getElementById('toastNotification');
        const toastTitle = document.getElementById('toastTitle');
        const toastMessage = document.getElementById('toastMessage');
        const toastIcon = document.getElementById('toastIcon');
        const closeToast = document.getElementById('closeToast');
        const toggleChartRefresh = document.getElementById('toggleChartRefresh');
        const chartRefresh = document.getElementById('chartRefresh');
        
        // 设置状态颜色
        function statusColor(status) {
            if (status === 'running') return 'text-success';
            else if (status === 'sleeping') return 'text-gray-400';
            else if (status === 'stopped') return 'text-warning';
            else if (status === 'zombie') return 'text-danger';
            return 'text-gray-300';
        }
        
        // 设置CPU颜色
        function cpuColor(percent) {
            if (percent > 75) return 'text-danger';
            else if (percent > 50) return 'text-warning';
            else if (percent > 25) return 'text-success';
            return 'text-gray-300';
        }
        
        // 设置内存颜色
        function memoryColor(percent) {
            if (percent > 75) return 'text-danger';
            else if (percent > 50) return 'text-warning';
            else if (percent > 25) return 'text-success';
            return 'text-gray-300';
        }
        
        // 初始化 CPU 图表
        function initCpuChart() {
            const ctx = document.getElementById('cpuChart').getContext('2d');
            cpuChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'CPU 使用率 (%)',
                        data: [],
                        borderColor: '#165DFF',
                        backgroundColor: 'rgba(22, 93, 255, 0.1)',
                        fill: true,
                        tension: 0.4,
                        borderWidth: 2,
                        pointRadius: 0,
                        pointHoverRadius: 4,
                        pointBackgroundColor: '#165DFF'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        x: {
                            grid: {
                                color: 'rgba(255, 255, 255, 0.05)'
                            },
                            ticks: {
                                color: 'rgba(255, 255, 255, 0.5)'
                            }
                        },
                        y: {
                            beginAtZero: true,
                            max: 100,
                            grid: {
                                color: 'rgba(255, 255, 255, 0.05)'
                            },
                            ticks: {
                                color: 'rgba(255, 255, 255, 0.5)'
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            labels: {
                                color: 'rgba(255, 255, 255, 0.7)'
                            }
                        }
                    },
                    interaction: {
                        intersect: false,
                        mode: 'index'
                    },
                    animation: {
                        duration: 0
                    }
                }
            });
        }
        
        // 格式化字节数
        function formatBytes(bytes, decimals = 2) {
            if (bytes === 0) return '0 Bytes';
            
            const k = 1024;
            const dm = decimals < 0 ? 0 : decimals;
            const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
            
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            
            return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
        }
        
        // 格式化时间戳为可读时间
        function formatTime(timestamp) {
            const date = new Date(timestamp * 1000);
            return date.toLocaleTimeString();
        }
        
        // 显示通知
        function showToast(title, message, isSuccess = true) {
            toastTitle.textContent = title;
            toastMessage.textContent = message;
            
            if (isSuccess) {
                toastIcon.innerHTML = '<i class="fa fa-check-circle text-success text-xl"></i>';
            } else {
                toastIcon.innerHTML = '<i class="fa fa-exclamation-circle text-danger text-xl"></i>';
            }
            
            toastNotification.classList.remove('translate-y-10', 'opacity-0');
            toastNotification.classList.add('translate-y-0', 'opacity-100');
            
            // 3秒后自动关闭
            setTimeout(hideToast, 3000);
        }
        
        // 隐藏通知
        function hideToast() {
            toastNotification.classList.remove('translate-y-0', 'opacity-100');
            toastNotification.classList.add('translate-y-10', 'opacity-0');
        }
        
        // 更新系统信息
        async function updateSystemInfo() {
            try {
                const response = await fetch('/api/system_info');
                if (!response.ok) throw new Error('网络请求失败');
                
                const data = await response.json();
                
                // 更新 CPU 信息
                document.getElementById('cpuPercent').textContent = `${data.cpu.percent}%`;
                document.getElementById('cpuCores').textContent = data.cpu.count;
                document.getElementById('cpuCoresLogical').textContent = data.cpu.count_logical;
                document.getElementById('cpuBar').style.width = `${data.cpu.percent}%`;
                
                // 更新内存信息
                const memoryUsed = formatBytes(data.memory.used);
                const memoryTotal = formatBytes(data.memory.total);
                document.getElementById('memoryPercent').textContent = `${data.memory.percent}%`;
                document.getElementById('memoryUsed').textContent = memoryUsed;
                document.getElementById('memoryTotal').textContent = memoryTotal;
                document.getElementById('memoryBar').style.width = `${data.memory.percent}%`;
                
                // 更新磁盘信息
                const diskUsed = formatBytes(data.disk.used);
                const diskTotal = formatBytes(data.disk.total);
                document.getElementById('diskPercent').textContent = `${data.disk.percent}%`;
                document.getElementById('diskUsed').textContent = diskUsed;
                document.getElementById('diskTotal').textContent = diskTotal;
                document.getElementById('diskBar').style.width = `${data.disk.percent}%`;
                
                // 更新网络信息
                const now = data.timestamp;
                const currentNetworkData = {
                    bytes_sent: data.network.bytes_sent,
                    bytes_recv: data.network.bytes_recv,
                    timestamp: now
                };
                
                if (lastNetworkData) {
                    const timeDiff = now - lastNetworkData.timestamp;
                    const sentRate = Math.round((currentNetworkData.bytes_sent - lastNetworkData.bytes_sent) / timeDiff);
                    const recvRate = Math.round((currentNetworkData.bytes_recv - lastNetworkData.bytes_recv) / timeDiff);
                    
                    document.getElementById('networkSent').textContent = `${formatBytes(sentRate)}/s`;
                    document.getElementById('networkRecv').textContent = `↓ ${formatBytes(recvRate)}/s`;
                }
                
                document.getElementById('totalSent').textContent = formatBytes(currentNetworkData.bytes_sent);
                document.getElementById('totalRecv').textContent = formatBytes(currentNetworkData.bytes_recv);
                
                lastNetworkData = currentNetworkData;
                
                // 更新时间
                const nowDate = new Date();
                updateTime.textContent = `更新于: ${nowDate.getHours().toString().padStart(2, '0')}:${nowDate.getMinutes().toString().padStart(2, '0')}:${nowDate.getSeconds().toString().padStart(2, '0')}`;
                
                // 更新 CPU 图表
                if (chartRefreshEnabled && data.cpu.history.length > 0) {
                    const labels = data.cpu.history.map(h => formatTime(h[0]));
                    const values = data.cpu.history.map(h => h[1]);
                    
                    cpuChart.data.labels = labels;
                    cpuChart.data.datasets[0].data = values;
                    cpuChart.update();
                }
                
                return true;
            } catch (error) {
                console.error('更新系统信息失败:', error);
                showToast('更新失败', '无法获取系统信息', false);
                return false;
            }
        }
        
        // 更新进程列表
        async function updateProcessList() {
            try {
                const searchTerm = processSearch.value.toLowerCase();
                const sortField = sortBy.value;
                
                processTableBody.innerHTML = `
                    <tr class="animate-pulse">
                        <td colspan="7" class="px-4 py-8 text-center text-gray-400">
                            <i class="fa fa-spinner fa-spin mr-2"></i>加载进程中...
                        </td>
                    </tr>
                `;
                
                const response = await fetch(`/api/processes?sort_by=${sortField}&order=${sortOrder}&search=${searchTerm}`);
                if (!response.ok) throw new Error('网络请求失败');
                
                const processes = await response.json();
                
                if (processes.length === 0) {
                    noProcessesFound.classList.remove('hidden');
                    processTableBody.innerHTML = '';
                } else {
                    noProcessesFound.classList.add('hidden');
                    processTableBody.innerHTML = '';
                    
                    processes.forEach(process => {
                        const row = document.createElement('tr');
                        row.className = 'hover:bg-dark/50 transition-colors';
                        
                        // 设置CPU使用率的颜色
                        let cpuColor = 'text-gray-300';
                        if (process.cpu_percent > 75) cpuColor = 'text-danger';
                        else if (process.cpu_percent > 50) cpuColor = 'text-warning';
                        else if (process.cpu_percent > 25) cpuColor = 'text-success';
                        
                        // 设置内存使用率的颜色
                        let memoryColor = 'text-gray-300';
                        if (process.memory_percent > 75) memoryColor = 'text-danger';
                        else if (process.memory_percent > 50) memoryColor = 'text-warning';
                        else if (process.memory_percent > 25) memoryColor = 'text-success';
                        
                        // 设置状态的颜色
                        let statusColor = 'text-gray-300';
                        if (process.status === 'running') statusColor = 'text-success';
                        else if (process.status === 'sleeping') statusColor = 'text-gray-400';
                        else if (process.status === 'stopped') statusColor = 'text-warning';
                        else if (process.status === 'zombie') statusColor = 'text-danger';
                        
                        row.innerHTML = `
                            <td class="px-4 py-3 whitespace-nowrap">
                                <div class="font-medium text-gray-300">${process.pid}</div>
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap">
                                <div class="font-medium text-gray-300">${process.name}</div>
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap">
                                <div class="text-gray-400">${process.username}</div>
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap">
                                <div class="${cpuColor}">${process.cpu_percent.toFixed(1)}</div>
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap">
                                <div class="${memoryColor}">${process.memory_percent.toFixed(1)}</div>
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap">
                                <div class="${statusColor}">${process.status}</div>
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap">
                                <button data-pid="${process.pid}" data-name="${process.name}" class="view-details bg-primary/20 hover:bg-primary/30 text-primary px-3 py-1 rounded transition-colors">
                                    <i class="fa fa-info-circle mr-1"></i> 详情
                                </button>
                            </td>
                        `;
                        
                        processTableBody.appendChild(row);
                    });
                    
                    // 添加事件监听器
                    document.querySelectorAll('.view-details').forEach(button => {
                        button.addEventListener('click', () => {
                            const pid = button.getAttribute('data-pid');
                            const name = button.getAttribute('data-name');
                            openProcessDetails(pid, name);
                        });
                    });
                }
                
                return true;
            } catch (error) {
                console.error('更新进程列表失败:', error);
                showToast('更新失败', '无法获取进程信息', false);
                return false;
            }
        }
        
        // 打开进程详情
        async function openProcessDetails(pid, name) {
            currentProcessPid = pid;
            modalTitle.textContent = `进程详情: ${name} (PID: ${pid})`;
            modalBody.innerHTML = `
                <div class="flex justify-center items-center h-40">
                    <i class="fa fa-spinner fa-spin text-3xl text-gray-400"></i>
                </div>
            `;
            
            // 显示模态框
            processDetailsModal.classList.remove('hidden');
            setTimeout(() => {
                modalContent.classList.remove('scale-95', 'opacity-0');
                modalContent.classList.add('scale-100', 'opacity-100');
            }, 10);
            
            try {
                // 获取进程详情
                const response = await fetch(`/api/processes?sort_by=pid&order=asc&search=${pid}`);
                if (!response.ok) throw new Error('网络请求失败');
                
                const processes = await response.json();
                const process = processes.find(p => p.pid == pid);
                
                if (!process) {
                    modalBody.innerHTML = `
                        <div class="text-center py-8">
                            <i class="fa fa-exclamation-circle text-danger text-4xl mb-4"></i>
                            <p class="text-gray-300">无法获取进程信息</p>
                            <p class="text-gray-400 text-sm mt-2">进程可能已终止</p>
                        </div>
                    `;
                    return;
                }
                
                modalBody.innerHTML = `
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <h4 class="text-gray-400 text-sm font-medium mb-2">基本信息</h4>
                            <div class="bg-dark p-4 rounded-lg">
                                <div class="space-y-3">
                                    <div class="flex justify-between">
                                        <span class="text-gray-400">PID:</span>
                                        <span class="font-medium">${process.pid}</span>
                                    </div>
                                    <div class="flex justify-between">
                                        <span class="text-gray-400">名称:</span>
                                        <span class="font-medium">${process.name}</span>
                                    </div>
                                    <div class="flex justify-between">
                                        <span class="text-gray-400">用户:</span>
                                        <span class="font-medium">${process.username}</span>
                                    </div>
                                    <div class="flex justify-between">
                                        <span class="text-gray-400">状态:</span>
                                        <span class="font-medium ${statusColor(process.status)}">${process.status}</span>
                                    </div>
                                    <div class="flex justify-between">
                                        <span class="text-gray-400">创建时间:</span>
                                        <span class="font-medium">${process.create_time}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div>
                            <h4 class="text-gray-400 text-sm font-medium mb-2">资源使用</h4>
                            <div class="bg-dark p-4 rounded-lg">
                                <div class="space-y-3">
                                    <div>
                                        <div class="flex justify-between mb-1">
                                            <span class="text-gray-400">CPU 使用率:</span>
                                            <span class="font-medium ${cpuColor(process.cpu_percent)}">${process.cpu_percent.toFixed(1)}%</span>
                                        </div>
                                        <div class="h-2 bg-dark-3 rounded-full overflow-hidden">
                                            <div class="h-full bg-primary rounded-full" style="width: ${process.cpu_percent}%"></div>
                                        </div>
                                    </div>
                                    
                                    <div>
                                        <div class="flex justify-between mb-1">
                                            <span class="text-gray-400">内存使用率:</span>
                                            <span class="font-medium ${memoryColor(process.memory_percent)}">${process.memory_percent.toFixed(1)}%</span>
                                        </div>
                                        <div class="h-2 bg-dark-3 rounded-full overflow-hidden">
                                            <div class="h-full bg-secondary rounded-full" style="width: ${process.memory_percent}%"></div>
                                        </div>
                                    </div>
                                    
                                    <div>
                                        <div class="flex justify-between mb-1">
                                            <span class="text-gray-400">内存使用量:</span>
                                            <span class="font-medium">${formatBytes(process.memory_info.rss)}</span>
                                        </div>
                                        <div class="flex justify-between mb-1">
                                            <span class="text-gray-400">线程数:</span>
                                            <span class="font-medium">${process.num_threads}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mt-6">
                        <h4 class="text-gray-400 text-sm font-medium mb-2">进程命令行</h4>
                        <div class="bg-dark p-4 rounded-lg">
                            <pre class="text-gray-300 text-sm font-mono overflow-x-auto">${process.cmdline.join(' ')}</pre>
                        </div>
                    </div>
                `;
                
                // 绑定终止进程按钮
                document.getElementById('terminateProcessBtn').addEventListener('click', async () => {
                    try {
                        const response = await fetch(`/api/processes/${pid}/terminate`, { method: 'POST' });
                        const data = await response.json();
                        
                        if (response.ok) {
                            showToast('操作成功', data.message);
                            updateProcessList();
                            closeModal.click();
                        } else {
                            showToast('操作失败', data.message, false);
                        }
                    } catch (error) {
                        showToast('操作失败', '无法终止进程', false);
                    }
                });
                
                // 绑定刷新进程信息按钮
                document.getElementById('refreshProcessBtn').addEventListener('click', () => {
                    openProcessDetails(pid, name);
                });
                
            } catch (error) {
                console.error('获取进程详情失败:', error);
                modalBody.innerHTML = `
                    <div class="text-center py-8">
                        <i class="fa fa-exclamation-circle text-danger text-4xl mb-4"></i>
                        <p class="text-gray-300">获取进程详情失败</p>
                        <p class="text-gray-400 text-sm mt-2">${error.message}</p>
                    </div>
                `;
            }
        }
        
        // 终止进程
        async function terminateProcess(pid) {
            try {
                const response = await fetch(`/api/processes/${pid}/terminate`, { method: 'POST' });
                const data = await response.json();
                
                if (response.ok) {
                    showToast('操作成功', data.message);
                    updateProcessList();
                } else {
                    showToast('操作失败', data.message, false);
                }
            } catch (error) {
                console.error('终止进程失败:', error);
                showToast('操作失败', '无法终止进程', false);
            }
        }
        
        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            initCpuChart();
            updateSystemInfo();
            updateProcessList();
            
            // 设置定时更新
            setInterval(updateSystemInfo, 2000);
            setInterval(updateProcessList, 5000);
            
            // 绑定事件监听器
            refreshBtn.addEventListener('click', () => {
                updateSystemInfo();
                updateProcessList();
            });
            
            sortOrderBtn.addEventListener('click', () => {
                sortOrder = sortOrder === 'asc' ? 'desc' : 'asc';
                sortOrderBtn.innerHTML = sortOrder === 'asc' ? '<i class="fa fa-sort-asc"></i>' : '<i class="fa fa-sort-desc"></i>';
                updateProcessList();
            });
            
            sortBy.addEventListener('change', updateProcessList);
            processSearch.addEventListener('input', updateProcessList);
            
            closeModal.addEventListener('click', () => {
                modalContent.classList.remove('scale-100', 'opacity-100');
                modalContent.classList.add('scale-95', 'opacity-0');
                setTimeout(() => {
                    processDetailsModal.classList.add('hidden');
                }, 300);
            });
            
            confirmTerminate.addEventListener('click', () => {
                if (currentProcessPid) {
                    terminateProcess(currentProcessPid);
                }
            });
            
            cancelTerminate.addEventListener('click', () => {
                closeModal.click();
            });
            
            closeToast.addEventListener('click', hideToast);
            
            toggleChartRefresh.addEventListener('click', () => {
                chartRefreshEnabled = !chartRefreshEnabled;
                chartRefresh.innerHTML = `自动刷新: <span class="${chartRefreshEnabled ? 'text-primary' : 'text-gray-400'}">${chartRefreshEnabled ? '开启' : '关闭'}</span>`;
                toggleChartRefresh.innerHTML = `<i class="fa ${chartRefreshEnabled ? 'fa-pause' : 'fa-play'}"></i>`;
            });
        });
    </script>
</body>
</html>